import React, { FC, useEffect } from 'react';
import { fabric } from 'fabric';

let downPoint: any = null; // 按下鼠标时的坐标
let upPoint: any = null; // 松开鼠标时的坐标

const FabricDemo: FC = () => {
  useEffect(() => {
    const canvas = new fabric.Canvas('canvas-fabrice', {
      isDrawingMode: false, // 开启绘图模式
    });

    canvas.on('mouse:down', canvasMouseDown); // 鼠标在画布上按下
    canvas.on('mouse:up', (e) => canvasMouseUp(e, canvas)); // 鼠标在画布上松开

    canvas.selectionColor = 'transparent';
    canvas.selectionBorderColor = 'rgba(0, 0, 0, 0.2)';
    canvas.skipTargetFind = true; // 禁止选中

    // 矩形对象
    const rect = new fabric.Rect({
      top: 10,
      left: 10,
      width: 100,
      height: 100,
      fill: 'transparent', // 填充色：透明
      stroke: '#000', // 边框颜色：黑色
    });

    // 将矩形添加到画布上
    canvas.add(rect);
  }, []);

  const canvasMouseDown = (e) => {
    // 鼠标左键按下时，将当前坐标 赋值给 downPoint。{x: xxx, y: xxx} 的格式
    downPoint = e.absolutePointer;
  };
  const canvasMouseUp = (e, canvas) => {
    // 松开鼠标左键时，将当前坐标 赋值给 upPoint
    upPoint = e.absolutePointer;
    createRect(canvas);
  };

  // 创建矩形
  function createRect(canvas) {
    // 如果点击和松开鼠标，都是在同一个坐标点，不会生成矩形
    if (JSON.stringify(downPoint) === JSON.stringify(upPoint)) {
      return;
    }
    if (!downPoint || !upPoint) return;

    // 创建矩形
    // 矩形参数计算（前面总结的4条公式）
    let top = Math.min(downPoint.y, upPoint.y);
    let left = Math.min(downPoint.x, upPoint.x);
    let width = Math.abs(downPoint.x - upPoint.x);
    let height = Math.abs(downPoint.y - upPoint.y);

    // 矩形对象
    const rect = new fabric.Rect({
      top,
      left,
      width,
      height,
      fill: 'transparent', // 填充色：透明
      stroke: '#000', // 边框颜色：黑色
    });

    // 将矩形添加到画布上
    canvas.add(rect);

    // 创建完矩形，清空 downPoint 和 upPoint。当然，你也可以不做这步。
    downPoint = null;
    upPoint = null;
  }

  return (
    <>
      <h1>fail demo</h1>
      <canvas
        id="canvas-fabrice"
        width="800"
        height="800"
        style={{ border: '1px solid' }}
      ></canvas>
    </>
  );
};

export default FabricDemo;
